﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Controller;
using Entity;

namespace Web
{
    public partial class EditCustomerPO : System.Web.UI.Page
    {
        Helper helper = new Helper();
        protected void Page_Load(object sender, EventArgs e)
        {
           
            if (!IsPostBack)
            {
                if (Request.QueryString["customerPOId"] != null)
                {
                    int custPOId = Convert.ToInt32(Request.QueryString["customerPOId"]);
                    CustomerPOController CustomerPoController = new CustomerPOController();
                    CustomerPOEntity CustomerPoEntity = CustomerPoController.findCustomerPOById(custPOId);
                    //if (CustomerPoEntity.Status != "new")//if the items of this po have been stock in partial or finished, cannot update this po
                    //{
                        //SubmitButton.Enabled = false;
                    //}
                    //else
                    //{
                        CustomerPOItemController CustomerPoItemController = new CustomerPOItemController();
                        IList<CustomerPOItemEntity> CustomerPoItemEntities =
                            CustomerPoItemController.findCustomerPOItemsByCustPOId(custPOId);
                        CustomerPOItemGridView.DataSource = CustomerPoItemEntities;
                        CustomerPOItemGridView.DataBind();
                        Session["CustomerPOItems"] = CustomerPoItemEntities;
                        CustomerController CustomerController = new CustomerController();
                        IList<CustomerEntity> CustomerEntities = CustomerController.finAllCustomers();
                        CustomerDropDownList.DataSource = CustomerEntities;
                        CustomerDropDownList.DataValueField = "Id";
                        CustomerDropDownList.DataTextField = "ShortName";
                        CustomerDropDownList.DataBind();

                        //Bind the Customer po info.
                        CustomerPONoTextBox.Text = CustomerPoEntity.No;
                        POTypeRadioButtonList.SelectedValue = CustomerPoEntity.Type;
                        POTypeRadioButtonList.Enabled = false;
                        CustomerDropDownList.SelectedValue = CustomerPoEntity.CustId.ToString();
                        PODateTextBox.Text =CustomerPoEntity.Date.ToString("dd MMM, yyyy");
                        if(CustomerPoEntity.Address!=string.Empty)
                        {
                            string[] address = CustomerPoEntity.Address.Split(',');
                            if (address.Length==3)
                            {
                                AddressTextBox1.Text = address[0];
                                AddressTextBox2.Text = address[1];
                                AddressTextBox3.Text = address[2];
                            }
                            else if(address.Length==2)
                            {
                                AddressTextBox1.Text = address[0];
                                AddressTextBox2.Text = address[1];
                                AddressTextBox3.Text = "";
                            }
                            else if(address.Length==1)
                            {
                                AddressTextBox1.Text = address[0];
                                AddressTextBox2.Text = "";
                                AddressTextBox3.Text = "";
                            }
                            else
                            {
                                AddressTextBox1.Text = "";
                                AddressTextBox2.Text = "";
                                AddressTextBox3.Text = "";
                            }
                        }

                        AttentionTextBox.Text = CustomerPoEntity.Attention;
                        PhoneTextBox.Text = CustomerPoEntity.Phone;
                        FaxTextBox.Text = CustomerPoEntity.Fax;
                        ZipCodeTextBox.Text = CustomerPoEntity.ZipCode;
                        CreatedByTextBox.Text = CustomerPoEntity.CreatedBy.ToString();
                        ApprovedByTextBox.Text = CustomerPoEntity.ApprovedBy.ToString();
                        RefereceTextBox.Text = CustomerPoEntity.Reference;
                        RemarkTextBox.Text = CustomerPoEntity.Remark;
                        TotalQtyTextBox.Text = CustomerPoEntity.TotalQty.ToString();

                        SummaryPOTypeLabel.Text = CustomerPoEntity.Type;
                        SummaryTotalOpenQtyLabel.Text = CustomerPoEntity.TotalOpenQty.ToString();

                        //Bind the Insert area drop down
                        ProductController productController = new ProductController();
                        IList<ProductEntity> productEntities = productController.FindAllProductEntities();
                        NoAndRevDropDownList.DataSource = productEntities;
                        NoAndRevDropDownList.DataValueField = "Id";
                        NoAndRevDropDownList.DataTextField = "ProductNoAndRevision";
                        NoAndRevDropDownList.DataBind();
                        NoAndRevDropDownList.Items.Insert(0, new ListItem("--Select Product--", "0"));
                        InsertButton.Enabled = false;
                        //Set today to insert requested date textbox calendar
                        InsertRequestedDateTextBox_CalendarExtender.SelectedDate = System.DateTime.Now;

                    //}
                }
                else
                {
                    int custPOId = Convert.ToInt32(Request.QueryString["customerPOId"]);
                    Response.Redirect("CustomerPODetail.aspx" + custPOId);
                }
            }
            this.PreRender += new EventHandler(UpdateFlashMessage);
        }
        private void UpdateFlashMessage(object sender, EventArgs e)
        {
            helper.ShowFlashMessage(FlashMessageLabel);
        }

        protected void InsertButton_Click(object sender, EventArgs e)
        {
            IList<CustomerPOItemEntity> CustomerPOItemEntities = Session["CustomerPOItems"] as IList<CustomerPOItemEntity>;
            CustomerPOItemEntity CustomerPOItemEntity = new CustomerPOItemEntity();
            ProductEntity productEntity = this.ConstructProductEntity();
            ProductNameLabel.Text = productEntity.Name;

            CustomerPOItemEntity.ProductId = productEntity.Id;
            CustomerPOItemEntity.ProductNo = productEntity.No;
            CustomerPOItemEntity.ProductName = productEntity.Name;
            CustomerPOItemEntity.Revision = productEntity.Revision;
            CustomerPOItemEntity.RequestDate = Convert.ToDateTime(InsertRequestedDateTextBox.Text.Trim());
            CustomerPOItemEntity.Price = Convert.ToDecimal(InsertPriceTextBox.Text.Trim());
            CustomerPOItemEntity.Lot = Convert.ToInt32(InsertLotTextBox.Text.Trim());
            CustomerPOItemEntity.RequestQty = Convert.ToInt32(InsertQtyTextBox.Text.Trim());
            CustomerPOItemEntity.ProductNoAndRevision = NoAndRevDropDownList.SelectedItem.Text.Trim();
            CustomerPOItemEntity.FormatDate = InsertRequestedDateTextBox.Text.Trim();
            CustomerPOItemEntity.Id = 0;
            CustomerPOItemEntity.Status = "new";
            CustomerPOItemEntities.Add(CustomerPOItemEntity);
            Session["CustomerPOItems"] = CustomerPOItemEntities;
            CustomerPOItemGridView.DataSource = CustomerPOItemEntities;
            CustomerPOItemGridView.DataBind();
        }

        protected void NoAndRevDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (NoAndRevDropDownList.SelectedIndex != 0)
            {
                InsertButton.Enabled = true;
                ProductEntity productEntity = this.ConstructProductEntity();
                ProductNameLabel.Text = productEntity.Name;
            }
            else
            {
                InsertButton.Enabled = false;
                ProductNameLabel.Text = "";
            }
        }
        private ProductEntity ConstructProductEntity()
        {
            int productId = Convert.ToInt32(NoAndRevDropDownList.SelectedValue);
            ProductController productController = new ProductController();
            ProductEntity productEntity = productController.FindProductById(productId);
            return productEntity;
        }
        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            try
            {
                int custPOId = Convert.ToInt32(Request.QueryString["customerPOId"]);
                CustomerPOItemController CustomerPoItemController = new CustomerPOItemController();
                //CustomerPoItemController.DeleteCustomerPOByCustomerPOId(custPOId);

                //Construct the new Customer po
                CustomerPOController CustomerPoController = new CustomerPOController();
                CustomerPOEntity CustomerPoEntity = new CustomerPOEntity();
                CustomerPoEntity.Id = custPOId;
                CustomerPoEntity.No = CustomerPONoTextBox.Text.Trim();
                CustomerPoEntity.CustId = Convert.ToInt32(CustomerDropDownList.SelectedValue);
                CustomerPoEntity.Phone = PhoneTextBox.Text.Trim();
                CustomerPoEntity.Reference = RefereceTextBox.Text.Trim();
                CustomerPoEntity.Remark = RemarkTextBox.Text.Trim();
                CustomerPoEntity.ZipCode = ZipCodeTextBox.Text.Trim();
                CustomerPoEntity.Address = AddressTextBox1.Text.Trim()+","+AddressTextBox2.Text.Trim()+","+AddressTextBox3.Text.Trim();
                CustomerPoEntity.ApprovedBy = Convert.ToInt32(ApprovedByTextBox.Text.Trim());
                CustomerPoEntity.CreatedBy = Convert.ToInt32(CreatedByTextBox.Text.Trim());
                CustomerPoEntity.Attention = AttentionTextBox.Text.Trim();
                CustomerPoEntity.Fax = FaxTextBox.Text.Trim();
                CustomerPoEntity.TotalQty = Convert.ToInt32(TotalQtyTextBox.Text);

                CustomerPoController.UpateCustomerPO(CustomerPoEntity);
                //IList<CustomerPOItemEntity> CustomerPOItemEntities =
                //    Session["CustomerPOItems"] as IList<CustomerPOItemEntity>;
                IList<CustomerPOItemEntity> CustomerPOItemEntities =new List<CustomerPOItemEntity>();
                   
                foreach (GridViewRow r  in CustomerPOItemGridView.Rows)
                {
                    CustomerPOItemEntity customerPoItemEntity=new CustomerPOItemEntity();
                    customerPoItemEntity.CustPOId = custPOId;
                    customerPoItemEntity.Lot = Convert.ToInt32(((TextBox)r.FindControl("LotTextBox")).Text);
                    customerPoItemEntity.Price = Convert.ToDecimal(((TextBox)r.FindControl("PriceTextBox")).Text);
                    customerPoItemEntity.ProductId =
                        (Session["CustomerPOItems"] as IList<CustomerPOItemEntity>)[r.RowIndex].ProductId;
                    customerPoItemEntity.Remark = ((TextBox) r.FindControl("RemarkTextBox")).Text;
                    customerPoItemEntity.RequestDate =Convert.ToDateTime(((TextBox) r.FindControl("RequestDateTextBox")).Text);
                    customerPoItemEntity.RequestQty = Convert.ToInt32(((TextBox)r.FindControl("QtyTextBox")).Text);
                    customerPoItemEntity.Status = (Session["CustomerPOItems"] as IList<CustomerPOItemEntity>)[r.RowIndex].Status;
                    customerPoItemEntity.Id = (Session["CustomerPOItems"] as IList<CustomerPOItemEntity>)[r.RowIndex].Id;
                    CustomerPOItemEntities.Add(customerPoItemEntity);
                    
                }
                Session["CustomerPOItems"] = CustomerPOItemEntities;
                foreach (CustomerPOItemEntity CustomerPoItemEntity in (Session["CustomerPOItems"] as IList<CustomerPOItemEntity>))
                {
                    if (CustomerPoItemEntity.Id == 0)
                    {
                        CustomerPoItemEntity.Status = "new";
                        //CustomerPoItemEntity.Remark = "";
                        //CustomerPoItemEntity.CustPoId = custPOId;
                        CustomerPoItemController.addCustomerPoItem(CustomerPoItemEntity);
                    }
                    else
                    {
                        CustomerPoItemController.UpdateCustomerPOItemByCustomerPOItemId(CustomerPoItemEntity);
                    }
                }
                Session["FlashMessage"] = "Success: Update Successful!";
                Session["FlashMessageType"] = "success";
            }
            catch(Exception ex)
            {
                Session["FlashMessage"] = "Error: "+ex.Message;
                Session["FlashMessageType"] = "error";
            }
        }

        protected void DeleteCustomerPOItemButton_Click(object sender, EventArgs e)
        {
            try
            {
                string msg = "";
                int rowIndex = ((GridViewRow)((Button)sender).NamingContainer).RowIndex;
                IList<CustomerPOItemEntity> CustomerPOItemEntities = Session["CustomerPOItems"] as IList<CustomerPOItemEntity>;
                int customerPOItemId = CustomerPOItemEntities[rowIndex].Id;
               
                CustomerPOItemController customerPoItemController=new CustomerPOItemController();
                customerPoItemController.DeleteCustomerPOItem(customerPOItemId,ref msg);
                if(msg=="")
                {
                    CustomerPOItemEntities.RemoveAt(rowIndex);
                    CustomerPOItemGridView.DataSource = CustomerPOItemEntities;
                    CustomerPOItemGridView.DataBind();
                }
                else
                {
                    Session["FlashMessage"] = "Error: " + "This record cannot be deleted!";
                    Session["FlashMessageType"] = "error";
                }
                Session["CustomerPOItems"] = CustomerPOItemEntities;
                

            }
            catch (Exception ex)
            {
                Session["FlashMessage"] = "Error: " + ex.Message;
                Session["FlashMessageType"] = "error";
            }
            
        }

        protected void CloseCustomerPOItemButton_Click(object sender, EventArgs e)
        {
            try
            {
                
           
            int rowIndex = ((GridViewRow)((Button)sender).NamingContainer).RowIndex;
            int massage = 0;
            IList<CustomerPOItemEntity> CustomerPOItemEntities = Session["CustomerPOItems"] as IList<CustomerPOItemEntity>;
            //string oldStatus = CustomerPOItemEntities[rowIndex].Status;
            //Session["OldStatus"] = oldStatus;
            if(Session["CloseOpen"]==null)
            {
                
                CustomerPOItemEntities[rowIndex].Status = "closed";
                Session["CloseOpen"] = "Closed";
                
                
            }
            else
            {
                if(Session["CloseOpen"].ToString()=="Closed")
                {
                    if (CustomerPOItemEntities[rowIndex].CompleteQty < CustomerPOItemEntities[rowIndex].RequestQty)
                    {
                        CustomerPOItemEntities[rowIndex].Status = "ongoing";
                    }
                    if (CustomerPOItemEntities[rowIndex].CompleteQty >= CustomerPOItemEntities[rowIndex].RequestQty)
                    {
                        CustomerPOItemEntities[rowIndex].Status = "completed";
                    }
                    if (CustomerPOItemEntities[rowIndex].CompleteQty ==0)
                    {
                        CustomerPOItemEntities[rowIndex].Status = "new";
                    }
                    
                   Session["CloseOpen"] = "Opened";
                   
                   
                }
                else
                {
                    if (Session["CloseOpen"].ToString() == "Opened")
                    {
                        CustomerPOItemEntities[rowIndex].Status = "closed";
                        Session["CloseOpen"] = "Closed";
                      
                    }
                }
                
            }
            Session["CustomerPOItems"] = CustomerPOItemEntities;
            CustomerPOItemGridView.DataSource = CustomerPOItemEntities;
            CustomerPOItemGridView.DataBind();
           }
            catch(Exception ex)
            {
                Session["FlashMessage"] = "Error: " + ex.Message;
                Session["FlashMessageType"] = "error";
            }

        }
    }
}